//
//  NetWorkTools.swift ----- 网络请求工具
//  WeiboSwift
//
//  Created by Apple13 on 16/7/11.
//  Copyright © 2016年 yupeng. All rights reserved.
//

import UIKit
import AFNetworking

enum RequsetType: Int {
    case GET
    case POST
}

class NetWorkTools: AFHTTPSessionManager {
    
    //单例
    static let shareTools: NetWorkTools = {
        let tools = NetWorkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
        
    }()

    
    //封装get/post请求
    func requset(type:RequsetType,url:String,params:AnyObject?, callBack:(response:AnyObject?,error:NSError?)->()){
        
        if type == RequsetType.GET {
           GET(url, parameters: params, progress: nil, success: { (_, response) in
            
            callBack(response: response,error: nil)
            
            }, failure: { (_, error) in
                callBack(response: nil,error: error)
           })
        }else{
            POST(url, parameters: params, progress: nil, success: { (_, response) in
                callBack(response: response,error: nil)
                }, failure: { (_, errer) in
                    callBack(response: nil,error: errer)
            })
            
        }
        
        
    }
    
    
    
}



//MARK: - 登录相关接口
extension NetWorkTools {
    
    //get AccessToken through 授权Code
    func requestAccesstoken(code:String,callBack:(response:AnyObject?,error:NSError?)->()){
        
        //接口地址
        let url = "https://api.weibo.com/oauth2/access_token"
        //准备参数
        let params = [
            "client_id": WeiboAppkey,
            "client_secret": WeiboAppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WeiboRedirect_Uri
        ]
        
        //使用通用接口去请求
        requset(.POST, url: url, params: params, callBack: callBack)
        
    }
    
    
    
    //获取用户信息
    func requestUserInfo(userAccount:UserAccount,callBack:(response: AnyObject?, error: NSError?) -> ()){
        
        //接口地址
        let url = "https://api.weibo.com/2/users/show.json"
        
        //准备参数
        let params = [
        
            "access_token": userAccount.access_token!,
            "uid": "\(userAccount.uid)"
        
        ]
        requset(.GET, url: url, params: params, callBack: callBack)
        
    }
}

//MARK: - 首页微博相关接口

extension NetWorkTools{
    
    
    func loadStatus(callBack:(response:AnyObject?,error:NSError?)->()){
        
        //准备接口地址
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        //准备参数
        let params = [
            
            "access_token":UserAccountViewModel.shareUserAccount.accessToken!
        ]
        
        print(url + "?access_token=" + UserAccountViewModel.shareUserAccount.accessToken!)
        
        requset(.GET, url: url, params: params, callBack: callBack)
    }
    
    
}